package cn.stylefeng.guns.modular.gridsystem.tcp.VobrateTcp;


import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.json.JSONUtil;
import cn.stylefeng.guns.modular.gridsystem.websocket.WebSocketGatewayServer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Collections;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * netty客户端，调用websocket将振动数据发送给前端
 * @author cxy
 * @data 2023/6/10 9:25
 */

//@Configuration
@Slf4j
public class EchoServer implements CommandLineRunner, Ordered {
    // CommandLineRunner 或 ApplicationRunner

    @Value("${netty.tcp.port}")
    private Integer port;

    @Autowired
    @Lazy
    private static WebSocketGatewayServer webSocketGatewayServer = new WebSocketGatewayServer();

    private static final CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>();

    @Override
    public void run(String... args) throws Exception {
        /**
         *    Netty客户端只有一个NioEventLoopGroup，就是用来处理与服务端通信的线程组
         *    NioEventLoopGroup可以理解为一个线程池，内部维护了一组线程，每个线程负责处理多个Channel上的事件，
         *    而一个Channel只对应于一个线程，这样可以回避多线程下的数据同步问题
         *    选择器Selector的获取和注册
         */

/*       NioEventLoopGroup boss = new NioEventLoopGroup(1);
        NioEventLoopGroup  worker = new NioEventLoopGroup();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(boss,worker)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline().addLast(new ChannelInboundHandlerAdapter(){
                                @Override
                                public void channelActive(ChannelHandlerContext ctx) throws Exception {
                                    super.channelActive(ctx);
                                }
                                @Override
                                public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                    //持续接收客户端发送的信息
                                    byte[] bytes = ByteBufUtil.getBytes((ByteBuf) msg);
                                    String s = new String(bytes);
                                    String[] split = s.split(":");

                                    Collections.addAll(list,split);
                                    //通过websocket发送给前端，每次先发完之后删除前10个，加入新数据
                                    if (EchoServer.list.size()>400) {
                                        String s2 = JSONUtil.toJsonStr(EchoServer.list);
                                        ThreadUtil.execAsync(()->{
                                            try {
                                                webSocketGatewayServer.sendVibrationMessage(s2);
                                            } catch (IOException e) {
                                                log.error("#发送振动消息失败:{}",e.getMessage());
                                            }
                                        });
                                        //List<String> list1 = EchoServer.list.subList(300, EchoServer.list.size());
                                        //EchoServer.list.removeAll(list1);
                                        for (int i = 0; i < 10; i++) {
                                            EchoServer.list.remove(i);
                                        }
                                    }

                                }
                            });
                        }
                    });
            ChannelFuture sync = serverBootstrap.bind(port).sync();// 绑定端口，开始接收进来的连接
            log.info("netty-tcp--> EchoServer server启动成功");
            // 对关闭通道进行监听
            sync.channel().closeFuture().await();
        }finally {
            worker.shutdownGracefully();
            boss.shutdownGracefully();
        }*/
    }

    @Override
    public int getOrder() {
        return LOWEST_PRECEDENCE;
    }
}
